package com.atguigu.day07;

import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.co.ProcessJoinFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

public class Flink07_IntervalJoin_Output {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        KeyedStream<Tuple2<String, Integer>, Tuple> orderKeyedStream = env
                .socketTextStream("localhost",9999)
                .map(new MapFunction<String, Tuple2<String,Integer>>() {
                    @Override
                    public Tuple2<String, Integer> map(String value) throws Exception {
                        String[] split = value.split(",");
                        return Tuple2.of(split[0],Integer.parseInt(split[1]));
                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<Tuple2<String, Integer>>forMonotonousTimestamps()
                                .withTimestampAssigner((value, ts) -> value.f1 * 1000L)
                )
                .keyBy("f0");
        orderKeyedStream.process(new ProcessFunction<Tuple2<String, Integer>, String>() {
            @Override
            public void processElement(Tuple2<String, Integer> value, ProcessFunction<Tuple2<String, Integer>, String>.Context ctx, Collector<String> out) throws Exception {
                System.out.println("order:"+ctx.timerService().currentWatermark());
            }
        });



        KeyedStream<Tuple3<String, Integer, String>, Tuple> skuKeyedStream = env
                .socketTextStream("localhost",8888)
                .map(new MapFunction<String, Tuple3<String,Integer,String>>() {
                    @Override
                    public Tuple3<String, Integer, String> map(String value) throws Exception {
                        String[] split = value.split(",");
                        return Tuple3.of(split[0],Integer.parseInt(split[1]),split[2]);
                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<Tuple3<String, Integer, String>>forMonotonousTimestamps()
                                .withTimestampAssigner((value, ts) -> value.f1 * 1000L)
                )
                .keyBy("f0");

        skuKeyedStream.process(new ProcessFunction<Tuple3<String, Integer, String>, String>() {
            @Override
            public void processElement(Tuple3<String, Integer, String> value, ProcessFunction<Tuple3<String, Integer, String>, String>.Context ctx, Collector<String> out) throws Exception {
                System.out.println("sku:"+ctx.timerService().currentWatermark());
            }
        });

        OutputTag<Tuple3<String, Integer, String>> skuOutPutTag = new OutputTag<Tuple3<String, Integer, String>>("skuStream", Types.TUPLE(Types.STRING,Types.INT,Types.STRING)) {
        };
        OutputTag<Tuple2<String, Integer>> orderOutPutTag = new OutputTag<Tuple2<String, Integer>>("orderStream",Types.TUPLE(Types.STRING, Types.INT)) {
        };

        //拿两条流做间隔链接 关联用户下单前后10S浏览了哪些商品
        SingleOutputStreamOperator<String> result = orderKeyedStream.intervalJoin(skuKeyedStream)
//
//                * 1、只支持事件时间
//                * 2、指定上界、下界的偏移，负号代表时间往前，正号代表时间往后
//                * 3、process中，只能处理 join上的数据
//         * 4、两条流关联后的watermark，以两条流中最小的为准
//                * 5、如果 当前数据的事件时间 < 当前的watermark，就是迟到数据， 主流的process不处理
//                *  => between后，可以指定将 左流 或 右流 的迟到数据 放入侧输出流

                .between(Time.seconds(-10), Time.seconds(10))
                .sideOutputLeftLateData(orderOutPutTag)
                .sideOutputRightLateData(skuOutPutTag)
                .process(new ProcessJoinFunction<Tuple2<String, Integer>, Tuple3<String, Integer, String>, String>() {
                    /**
                     * @param left  The left element of the joined pair.
                     * @param right The right element of the joined pair.
                     * @param ctx   A context that allows querying the timestamps of the left, right and joined pair.
                     *              In addition, this context allows to emit elements on a side output.
                     * @param out   The collector to emit resulting elements to.
                     * @throws Exception
                     */
                    @Override
                    public void processElement
                    (Tuple2<String, Integer> left, Tuple3<String, Integer, String> right, ProcessJoinFunction<Tuple2<String, Integer>, Tuple3<String, Integer, String>, String>.
                            Context ctx, Collector<String> out) throws Exception {
                        out.collect(left + "->" + right);
                    }
                });

        result.process(new ProcessFunction<String, String>() {
            @Override
            public void processElement(String value, ProcessFunction<String, String>.Context ctx, Collector<String> out) throws Exception {
                System.out.println("waterMark:" + ctx.timerService().currentWatermark());
            }
        });

        result.print("关联上的数据");
        result.getSideOutput(skuOutPutTag).print("右边侧流");
        result.getSideOutput(orderOutPutTag).print("左边侧流");

        env.execute();

    }
}
